package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.RoleMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description TODO
 * @ClassName RoleServiceImpl
 * @Author luhui
 * @date 2020.06.13 12:52
 * @version: 1.0
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        roleMapper.deleteRoleAndPermissionRelation(id);
        employeeMapper.deleteEmpAndRoleRelation(null,id);
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }


    @Override
    public void saveOrUpdate(Role role,Long[] permissionIds) {
        if (role.getId() == null){
            roleMapper.insert(role);
        }else {
            roleMapper.updateByPrimaryKey(role);
            roleMapper.deleteRoleAndPermissionRelation(role.getId());
        }

        if (permissionIds != null){
            for (Long permissionId : permissionIds) {
                roleMapper.insertRoleAndPermissionRelation(role.getId(),permissionId);
            }
        }
    }

    @Override
    public PageResult query(QueryObject queryObject) {
        int count = roleMapper.selectForCount(queryObject);
        if (count == 0){
            return PageResult.DEFAULT_PAGE;
        }

        List<Role> list = roleMapper.selectForList(queryObject);
        return new PageResult(queryObject.getCurrentPage(),queryObject.getPageSize(),list,count);
    }
}